//
//  HomeController.swift
//  SwiftDemo
//
//  Created by Steven on 2020/7/30.
//  Copyright © 2020 Steven. All rights reserved.
//

import UIKit
import MJRefresh


private let kSlideViewH = (kScreenWidth*135/375)
private let kPageViewCellId = "kPageViewCellId"
private let kADCellId = "kADCellId"


class HomeController: UIViewController {
    var promotionMoel:PromotionModel?
    var pageView : DXPageContentView?
    var menuTitleView:DXMenuTitleView?
    var canScroll = true
    var bannerView:DXBannerView?
    
    lazy var tableView:UITableView = {
        let tableView = UITableView(frame: view.bounds, style: UITableView.Style.plain)
        tableView.backgroundColor = .white
        tableView.delegate = self
        tableView.dataSource = self
        tableView.bounces = true
        tableView.showsVerticalScrollIndicator = false
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: kADCellId)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: kPageViewCellId)
        view.addSubview(tableView)
        return tableView
    }()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        title = "首页";
        view.backgroundColor = UIColor.white
        
        kNotife.addObserver(self, selector: #selector(changeScrollStatus), name:.kLeaveTop, object: nil)
        tableView.backgroundColor = .white
        tableView.mj_header = MJRefreshHeader(refreshingBlock: {
           [unowned self] in
            self.tableView.mj_header?.endRefreshing()
        });
        loadData()
        
        bannerView = DXBannerView()
        bannerView?.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kSlideViewH)
        tableView.tableHeaderView = bannerView
       
    }
    func loadData() {
        var params = [
            "area":"110000",
            "taskId":"",
            "menuCode":""
        ]
        
        if let userNo = UserInfo.instance?.userNo{
            params.updateValue(userNo, forKey: kUserNo)
        }
        NetworkManager.loadData(api: APIInterfacePromotion.queryPromoIndex(params: params), sucess: { [weak self](respons) -> (Void) in
            if respons.returnCode == KErrorCode.KErrorCode_SUCCESSE.rawValue {
                if let model = PromotionModel.deserialize(from: respons.toJSONString(),designatedPath: "data") {
                    self?.promotionMoel = model;
                    self?.tableView.reloadData()
                    self?.readLocalData()

                }
            }else{
                    self?.readLocalData()
            }
        }) { [weak self](error) -> (Void) in
            self?.readLocalData()
        }
        
    }
    func readLocalData(){
        let model = PromotionModel()
        DispatchQueue.global().async {
            let tempArr = JSONDeserializer<MenuModel>.deserializeModelArrayFrom(array: "menu".getLocalPlistData()) as! Array<MenuModel>
            model.menus = tempArr
            let tempArrBanner = JSONDeserializer<SlideShowModel>.deserializeModelArrayFrom(array: "homeBanner".getLocalPlistData()) as! Array<SlideShowModel>
            model.banners = tempArrBanner
            self.promotionMoel = model
            
            DispatchQueue.main.async {
                var urls:[String] = []
                if let banners = self.promotionMoel?.banners {
                     for bannerModel in banners {
                        urls.append(bannerModel.imgUrl ?? "")
                        urls.append(bannerModel.imgUrl ?? "")

                     }
                 }
                self.bannerView?.urls = urls
                self.tableView.reloadData()
                
                var subVCArr:[UIViewController] = []
                if let menus = self.promotionMoel?.menus{
                    for menuModel in menus {
                        let subVC = DXSubHomeController()
                        subVC.code = menuModel.code
                        subVCArr.append(subVC)
                    }
                }
                 
                self.pageView = DXPageContentView(frame: CGRect(x: 0, y: kSlideViewH, width: kScreenWidth, height: kScreenHeight-kSlideViewH), subVCArr: subVCArr, parentVC: self)
                self.view.addSubview(self.pageView!)
                self.pageView?.snp.makeConstraints({ (mk) in
                    mk.left.right.bottom.equalTo(self.view)
                    mk.top.equalTo(self.bannerView!).offset(kSlideViewH+40)
                })
            }
        }
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension HomeController:UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return kScreenHeight
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
 
        var titleArr = [String]()
        promotionMoel?.menus?.forEach({ (menu) in
            if let title = menu.name{
                titleArr.append(title)
            }
        })
        
        menuTitleView = DXMenuTitleView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 40), titleArr: titleArr)
        menuTitleView?.menuMoveDelegate = self
        menuTitleView?.indicatoreType = .DXIndicatorTypeCustom
        menuTitleView?.indicatorExtension = 30
        return menuTitleView
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let contentCell = tableView.dequeueReusableCell(withIdentifier: kPageViewCellId, for: indexPath)
             
             return contentCell
    }
    

    
    @objc func changeScrollStatus(){
        
    }
    
}


extension HomeController:DXMenuMoveProtocol,DXContenteViewProtocol{
    func menuMoveProtocol(fromIndex: NSInteger, toIndex: NSInteger) {
        pageView?.currentIndex = toIndex
    }
    func pageContentViewDidScroll(fromIndex: NSInteger, toIndex: NSInteger) {
        menuTitleView?.selectedIndex = toIndex
    }
}
